package com.treasure.infrastructure.index.loader;

import com.treasure.common.utils.ResourceReader;
import com.treasure.infrastructure.model.FileSegmentBean;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.Strings;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbsSegmentLoader {

    public List<FileSegmentBean> loadSegmentList(List<String> resourcePaths) throws IOException {
        if (CollectionUtils.isEmpty(resourcePaths)) {
            return Collections.emptyList();
        }

        List<FileSegmentBean> result = new ArrayList<>(resourcePaths.size());
        for (String resourcePath : resourcePaths) {
            String fileName = ResourceReader.getFileName(resourcePath);
            String settingString = ResourceReader.readStringFromResource(resourcePath);
            FileSegmentBean resourceSegmentBean = new FileSegmentBean();
            resourceSegmentBean.setFileName(fileName);
            List<String> segmentation = passagesSplit(settingString);
            resourceSegmentBean.setSegmentList(segmentation);
            result.add(resourceSegmentBean);

        }
        return result;
    }

    public List<String> passagesSplit(String resourceText) {
        if (!Strings.hasLength(resourceText)) {
            return Collections.emptyList();
        }
        return Arrays.stream(resourceText.split("\n")).filter(StringUtils::isNotBlank).collect(Collectors.toList());
    }
}
